package org.springblade.modules.device.service.impl;
import java.util.Date;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.QueriedLog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.aliemail.AliEmailProperties;
import org.springblade.modules.aliemail.AliEmailService;
import org.springblade.modules.alisls.AliSlsProperties;
import org.springblade.modules.alisls.AliyunSlsService;
import org.springblade.modules.device.config.DeviceProperties;
import org.springblade.modules.device.dto.DeviceAlertDto;
import org.springblade.modules.device.entity.*;
import org.springblade.modules.device.mapper.*;
import org.springblade.modules.device.service.IDeviceAlertService;
import org.springblade.modules.device.vo.DeviceAlertStatusVo;
import org.springblade.modules.device.vo.DeviceDetailVo;
import org.springblade.modules.device.vo.DeviceRunStatusVo;
import org.springblade.modules.device.vo.DeviceScarceStatusVo;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DeviceAlertServiceImpl implements IDeviceAlertService {
	@Resource
	private AliyunSlsService aliyunSlsService;
	@Resource
	private DeviceProperties deviceProperties;
	@Resource
	private DeviceAlertMapper deviceAlertMapper;
	@Resource
	private DeviceAlertHisMapper deviceAlertHisMapper;
	@Resource
	private DeviceAlertParamMapper deviceAlertParamMapper;
	@Resource
	private DeviceDetailMapper deviceDetailMapper;
	@Resource
	private AlertMailHisMapper alertMailHisMapper;

	private static final ExecutorService executors = Executors.newFixedThreadPool(6);

	@Override
	public List<?> getDeviceAlert(String alertType) {
		if(alertType.equals(DeviceAlert.RUN_STATUS_TYPE)){
			List<DeviceRunStatusVo> collect = getDeviceRunStatusVos();
			this.processAlert(collect);
			return collect;
		}else if(alertType.equals(DeviceAlert.SCARCE_STATUS_TYPE)){
			List<DeviceScarceStatusVo> collect = getDeviceScarceStatusVos();
			this.processScarceAlert(collect);
			return collect;
		}
		return new ArrayList<>();
	}

	@Nullable
	private List<DeviceRunStatusVo> getDeviceRunStatusVos() {
		LambdaQueryWrapper<DeviceAlertParam> deviceWrapper = Wrappers.lambdaQuery();
		deviceWrapper.eq(DeviceAlertParam::getAlertType,DeviceAlert.RUN_STATUS_TYPE);
		deviceWrapper.last("LIMIT 1");
		Date lastDate = Optional.ofNullable(deviceAlertParamMapper.selectOne(deviceWrapper)).map(DeviceAlertParam::getLastDateTime).orElse(null);
		Date start = null;
		if(null == lastDate){
			start = DateUtil.plusMinutes(new Date(), -5L);
		}else {
			start = lastDate;
		}

		int from = (int)(start.getTime()/1000);
		int to = (int)(System.currentTimeMillis() / 1000);
		List<QueriedLog> queriedLogs = aliyunSlsService.getDeviceRunStatus(deviceProperties.getAlert().getSlsProject(),deviceProperties.getAlert().getSlsLogStore(), deviceProperties.getAlert().getRunStatusTag(), from,to);

		List<DeviceRunStatusVo> collect = queriedLogs.stream().map(x -> {
			LogItem logItem = x.GetLogItem();
			String s = logItem.ToJsonString();
			logItem.ToJsonString();
			return JSON.parseObject(s, DeviceRunStatusVo.class);
		}).collect(Collectors.toList());
		return collect;
	}


	private void processAlert(List<DeviceRunStatusVo> deviceRunStatusVos){
		for (DeviceRunStatusVo deviceRunStatusVo : deviceRunStatusVos) {
			deviceRunStatusVo.setGroupTag(deviceRunStatusVo.getDeviceNo()+"|"+deviceRunStatusVo.getDeviceRunStatus());
		}
		//分组,每种只取一种状态,最新一条
		Map<String, List<DeviceRunStatusVo>> collect = deviceRunStatusVos.stream().collect(Collectors.groupingBy(DeviceRunStatusVo::getGroupTag));
		List<DeviceRunStatusVo> deviceRunStatusVos1 = new ArrayList<>();
		collect.forEach((k,v)->{
			v.sort(Comparator.comparing(DeviceRunStatusVo::getTime).reversed());
			DeviceRunStatusVo deviceRunStatusVo = v.stream().findFirst().get();
			deviceRunStatusVos1.add(deviceRunStatusVo);
		});
		//d3f3f542407aae4d
//		List<DeviceRunStatusVo> collect1 = deviceRunStatusVos.stream().filter(x -> "9050f682c78cf893".equals(x.getDeviceNo())).collect(Collectors.toList());
//		deviceRunStatusVos = collect1;
		deviceRunStatusVos1.sort(Comparator.comparing(DeviceRunStatusVo::getTime));
		for (DeviceRunStatusVo deviceRunStatusVo : deviceRunStatusVos1) {
			log.info("{}===>{}===>{}===>{}",deviceRunStatusVo.getDeviceNo(),deviceRunStatusVo.getDeviceRunStatus(),deviceRunStatusVo.getTime(),deviceRunStatusVo.getExceptionRemark());
			LambdaQueryWrapper<DeviceAlert> deviceWrapper = Wrappers.lambdaQuery();
			deviceWrapper.eq(DeviceAlert::getDeviceNo, deviceRunStatusVo.getDeviceNo());
			deviceWrapper.last("LIMIT 1");
			DeviceAlert deviceAlert = deviceAlertMapper.selectOne(deviceWrapper);
			boolean initDevice = false;
			if(null == deviceAlert){
				//生成一条
				DeviceAlert alert = new DeviceAlert();
				alert.setDeviceId(deviceRunStatusVo.getDeviceId());
				alert.setDeviceNo(deviceRunStatusVo.getDeviceNo());
				alert.setRunStatus(deviceRunStatusVo.getDeviceRunStatus());
				alert.setRunAlertUpdate(deviceRunStatusVo.getTime());
				deviceAlertMapper.insert(alert);
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				deviceAlert = alert;
				initDevice = true;
			}
			//异常记录
			DeviceAlertHis deviceAlertHis = new DeviceAlertHis();
			deviceAlertHis.setDeviceId(deviceRunStatusVo.getDeviceId());
			deviceAlertHis.setDeviceNo(deviceRunStatusVo.getDeviceNo());
			deviceAlertHis.setAlertType(DeviceAlert.RUN_STATUS_TYPE);
			deviceAlertHis.setAlertTime(deviceRunStatusVo.getTime());
			deviceAlertHis.setContent(deviceRunStatusVo.getExceptionRemark());
			deviceAlertHis.setOriginStatus(deviceRunStatusVo.getDeviceRunStatus());
			boolean isAlert = false;
			boolean isRestored = false;
			if (deviceRunStatusVo.getDeviceRunStatus()==2) {
				//初始化/上次状态正常则触发
				if (initDevice ||deviceAlert.getRunStatus() ==null || deviceAlert.getRunStatus()==1) {
					log.info("运行异常触发==={}===>{}",deviceRunStatusVo.getDeviceNo(),deviceRunStatusVo.getExceptionRemark());
					//之前是未告警则触发
					isAlert = true;
				}
			}else {
				if(deviceAlert.getRunStatus() == 2){
					log.info("运行恢复==={}===>{}",deviceRunStatusVo.getDeviceNo(),deviceRunStatusVo.getDeviceRunStatus());
//					deviceAlert.setRunStatus(deviceRunStatusVo.getDeviceRunStatus());
//					deviceAlert.setRunHisId(null);
//					deviceAlert.setRunAlertUpdate(deviceRunStatusVo.getTime());
//					deviceAlertMapper.updateById(deviceAlert);
					isRestored = true;
				}
			}
			deviceAlertHis.setIsAlert(isAlert);
			if(isAlert){
				String merchantEmail = getMerchantEmail(deviceRunStatusVo.getMerchantId());
//				merchantEmail = "497621708@qq.com";
				deviceAlertHis.setEmail(merchantEmail);
				deviceAlertHis.setIsSend(StringUtils.isNotBlank(merchantEmail));
			}
			deviceAlertHisMapper.insert(deviceAlertHis);
			if(isAlert){
				deviceAlert.setRunHisId(deviceAlertHis.getId());
				DeviceAlertDto deviceAlertDto = new DeviceAlertDto();
				deviceAlertDto.setDeviceRunStatus(deviceRunStatusVo.getDeviceRunStatus());
				deviceAlertDto.setDeviceAlertTag(DeviceAlertDto.TAG_RUN_STATUS);
				deviceAlertDto.setDeviceNo(deviceRunStatusVo.getDeviceNo());
				deviceAlertDto.setExceptionRemark(deviceRunStatusVo.getExceptionRemark());
				deviceAlertDto.setMerchantId(deviceRunStatusVo.getMerchantId());
				deviceAlertDto.setEmail(deviceAlertHis.getEmail());
				deviceAlertDto.setHisId(deviceAlertHis.getId());
				deviceAlertDto.setAlertTime(deviceAlertHis.getAlertTime());
				deviceAlertDto.setAlertType(deviceAlertHis.getAlertType());
				log.info("运行异常邮件推送===>{}",JSON.toJSONString(deviceAlertDto));
				CompletableFuture.runAsync(()->{
					sendAlert(deviceAlertDto);
				},executors);
			}
			if(isRestored){
				deviceAlert.setRunHisId(0L);
			}
			deviceAlert.setRunAlertUpdate(deviceRunStatusVo.getTime());
			deviceAlert.setRunStatus(deviceRunStatusVo.getDeviceRunStatus());
			deviceAlertMapper.updateById(deviceAlert);
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		CompletableFuture.runAsync(()->{
			updateQueryTime(deviceRunStatusVos);
		},executors);

	}

	private <T extends DeviceAlertStatusVo> void updateQueryTime(List<T> deviceRunStatusVos){
		List<Date> collect = deviceRunStatusVos.stream().map(DeviceAlertStatusVo::getTime).collect(Collectors.toList());
		if(collect.size()>0){
			Date date = collect.stream().max(Date::compareTo).get();
			LambdaUpdateWrapper<DeviceAlertParam> updateWrapper = Wrappers.lambdaUpdate();
			updateWrapper.eq(DeviceAlertParam::getAlertType,DeviceAlert.RUN_STATUS_TYPE);
			updateWrapper.set(DeviceAlertParam::getLastDateTime,date);
			int update = deviceAlertParamMapper.update(null, updateWrapper);
			if(update == 0){
				DeviceAlertParam entity = new DeviceAlertParam();
				entity.setLastDateTime(date);
				entity.setAlertType(DeviceAlert.RUN_STATUS_TYPE);
				deviceAlertParamMapper.insert(entity);
			}
		}
	}



	private List<DeviceScarceStatusVo> getDeviceScarceStatusVos() {
		LambdaQueryWrapper<DeviceAlertParam> deviceWrapper = Wrappers.lambdaQuery();
		deviceWrapper.eq(DeviceAlertParam::getAlertType,DeviceAlert.SCARCE_STATUS_TYPE);
		deviceWrapper.last("LIMIT 1");
		Date lastDate = Optional.ofNullable(deviceAlertParamMapper.selectOne(deviceWrapper)).map(DeviceAlertParam::getLastDateTime).orElse(null);
		Date start = null;
		if(null == lastDate){
			start = DateUtil.plusMinutes(new Date(), -5L);
		}else {
			start = lastDate;
		}

		int from = (int)(start.getTime()/1000);
		int to = (int)(System.currentTimeMillis() / 1000);
		List<QueriedLog> queriedLogs = aliyunSlsService.getDeviceRunStatus(deviceProperties.getAlert().getSlsProject(),deviceProperties.getAlert().getSlsLogStore(), deviceProperties.getAlert().getRunScarceTag(), from,to);

		List<DeviceScarceStatusVo> collect = queriedLogs.stream().map(x -> {
			LogItem logItem = x.GetLogItem();
			String s = logItem.ToJsonString();
			logItem.ToJsonString();
			return JSON.parseObject(s, DeviceScarceStatusVo.class);
		}).collect(Collectors.toList());
		return collect;
	}

	/**
	 * 物料告警触发
	 */
	private void processScarceAlert(List<DeviceScarceStatusVo> deviceScarceStatusVos){
		for (DeviceScarceStatusVo deviceScarceStatusVo: deviceScarceStatusVos) {
			deviceScarceStatusVo.setGroupTag(deviceScarceStatusVo.getDeviceNo()+"|"+deviceScarceStatusVo.getDeviceScarceStatus());
		}
		Map<String, List<DeviceScarceStatusVo>> collect = deviceScarceStatusVos.stream().collect(Collectors.groupingBy(DeviceScarceStatusVo::getGroupTag));
		List<DeviceScarceStatusVo> deviceScarceStatusVos1 = new ArrayList<>();
		collect.forEach((k,v)->{
			v.sort(Comparator.comparing(DeviceScarceStatusVo::getTime).reversed());
			DeviceScarceStatusVo deviceRunStatusVo = v.stream().findFirst().get();
			deviceScarceStatusVos1.add(deviceRunStatusVo);
		});
		deviceScarceStatusVos1.sort(Comparator.comparing(DeviceScarceStatusVo::getTime));
		for (DeviceScarceStatusVo deviceScarceStatusVo : deviceScarceStatusVos1) {
			log.info("物料{}===>{}===>{}===>{}",deviceScarceStatusVo.getDeviceNo(),deviceScarceStatusVo.getDeviceScarceStatus(),deviceScarceStatusVo.getTime(),deviceScarceStatusVo.getScarceRemark());
			LambdaQueryWrapper<DeviceAlert> deviceWrapper = Wrappers.lambdaQuery();
			deviceWrapper.eq(DeviceAlert::getDeviceNo, deviceScarceStatusVo.getDeviceNo());
			deviceWrapper.last("LIMIT 1");
			DeviceAlert deviceAlert = deviceAlertMapper.selectOne(deviceWrapper);
			boolean initDevice = false;
			if(null == deviceAlert){
				//生成一条
				DeviceAlert alert = new DeviceAlert();
				alert.setDeviceId(deviceScarceStatusVo.getDeviceId());
				alert.setDeviceNo(deviceScarceStatusVo.getDeviceNo());
				alert.setScarceStatus(deviceScarceStatusVo.getDeviceScarceStatus());
				alert.setRunAlertUpdate(deviceScarceStatusVo.getTime());
				deviceAlertMapper.insert(alert);
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				deviceAlert = alert;
				initDevice = true;
			}
			//异常记录
			DeviceAlertHis deviceAlertHis = new DeviceAlertHis();
			deviceAlertHis.setDeviceId(deviceScarceStatusVo.getDeviceId());
			deviceAlertHis.setDeviceNo(deviceScarceStatusVo.getDeviceNo());
			deviceAlertHis.setAlertType(DeviceAlert.SCARCE_STATUS_TYPE);
			deviceAlertHis.setAlertTime(deviceScarceStatusVo.getTime());
			deviceAlertHis.setContent(deviceScarceStatusVo.getScarceRemark());
			deviceAlertHis.setOriginStatus(deviceScarceStatusVo.getDeviceScarceStatus());
			boolean isAlert = false;
			boolean isRestored = false;
			if (deviceScarceStatusVo.getDeviceScarceStatus()==2 || deviceScarceStatusVo.getDeviceScarceStatus()==3) {
				//初始化/上次状态正常则触发
				if (initDevice || deviceAlert.getScarceStatus() == null || deviceAlert.getScarceStatus()==1) {
					log.info("物料告警触发==={}===>{}",deviceScarceStatusVo.getDeviceNo(),deviceScarceStatusVo.getScarceRemark());
					//之前是未告警则触发
					isAlert = true;
				}
			}else {
				if(deviceAlert.getScarceStatus() == 2 || deviceAlert.getScarceStatus() == 3){
					log.info("物料告警恢复==={}===>{}",deviceScarceStatusVo.getDeviceNo(),deviceScarceStatusVo.getScarceRemark());
//					deviceAlert.setScarceStatus(deviceScarceStatusVo.getDeviceScarceStatus());
//					deviceAlert.setScarceHisId(null);
//					deviceAlert.setScarceAlertUpdate(deviceScarceStatusVo.getTime());
//					deviceAlertMapper.updateById(deviceAlert);
					isRestored = true;
				}
			}
			deviceAlertHis.setIsAlert(isAlert);
			if(isAlert){
				String merchantEmail = getMerchantEmail(deviceScarceStatusVo.getMerchantId());
//				merchantEmail = "497621708@qq.com";
				deviceAlertHis.setEmail(merchantEmail);
				deviceAlertHis.setIsSend(StringUtils.isNotBlank(merchantEmail));

			}
			deviceAlertHisMapper.insert(deviceAlertHis);
			deviceAlert.setRunStatus(deviceScarceStatusVo.getDeviceScarceStatus());
			deviceAlert.setScarceAlertUpdate(deviceScarceStatusVo.getTime());
			if(isAlert){
				deviceAlert.setScarceHisId(deviceAlertHis.getId());
				DeviceAlertDto deviceAlertDto = new DeviceAlertDto();
				deviceAlertDto.setDeviceScarceStatus(deviceScarceStatusVo.getDeviceScarceStatus());
				deviceAlertDto.setScarceRemark(deviceScarceStatusVo.getScarceRemark());
				deviceAlertDto.setDeviceAlertTag(DeviceAlertDto.TAG_SCARCE_STATUS);
				deviceAlertDto.setDeviceNo(deviceScarceStatusVo.getDeviceNo());
				deviceAlertDto.setMerchantId(deviceScarceStatusVo.getMerchantId());
				deviceAlertDto.setEmail(deviceAlertHis.getEmail());
				deviceAlertDto.setHisId(deviceAlertHis.getId());
				deviceAlertDto.setAlertTime(deviceAlertHis.getAlertTime());
				deviceAlertDto.setAlertType(deviceAlertHis.getAlertType());
				log.info("物料异常邮件推送===>{}",JSON.toJSONString(deviceAlertDto));
				CompletableFuture.runAsync(()->{
					sendAlert(deviceAlertDto);
				},executors);
			}
			if(isRestored){
				deviceAlert.setScarceHisId(0L);
			}
			deviceAlertMapper.updateById(deviceAlert);
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		CompletableFuture.runAsync(()->{
			updateQueryTime(deviceScarceStatusVos);
		},executors);

	}



	private String getMerchantEmail(String merchantId){
		try {
			String url = SpringUtil.getBean(AliEmailProperties.class).getMerchantMailUrl()+merchantId;
			RestTemplate restTemplate = new RestTemplate();
			R<String> status = R.status(true);
			ResponseEntity<? extends R> forEntity = restTemplate.getForEntity(url, status.getClass());
			R<String> body = forEntity.getBody();
			return body.getData();
		} catch (Exception e) {
			log.error("获取用户邮箱失败",e);
			return "";
		}
	}



	public boolean sendAlert(DeviceAlertDto deviceAlertDto) {
		if (StringUtils.isBlank(deviceAlertDto.getEmail())) {
			log.info("merchantId未配置邮箱地址{}",deviceAlertDto.getMerchantId());
			return false;
		}
		String email = deviceAlertDto.getEmail();
		String content = "";
		boolean exceptionFlag = false;
		String alarmType = "";
		if(DeviceAlertDto.TAG_STATUS.equals(deviceAlertDto.getDeviceAlertTag())&&deviceAlertDto.getStatus()==2){
			content = "Device offline";
			exceptionFlag = true;
			alarmType = "Device onlineStatus";
		}else if(DeviceAlertDto.TAG_RUN_STATUS.equals(deviceAlertDto.getDeviceAlertTag())&&deviceAlertDto.getDeviceRunStatus()==2){
			content = deviceAlertDto.getExceptionRemark();
			exceptionFlag = true;
			alarmType = "device exception";
		}else if(DeviceAlertDto.TAG_SCARCE_STATUS.equals(deviceAlertDto.getDeviceAlertTag())&&(deviceAlertDto.getDeviceScarceStatus()==2||deviceAlertDto.getDeviceScarceStatus() ==3)){
			content = deviceAlertDto.getScarceRemark();
			exceptionFlag = true;
			alarmType = "missing ingredients ";
		}
		log.info("告警推送{}=>{}===>{}",exceptionFlag,email,content);
		if(exceptionFlag){
			if (this.checkMailLimit(deviceAlertDto)) {
				return false;
			}
			log.info("告警推送文本{}===>{}",email,content);
			String s = buildEmailBody(deviceAlertDto.getDeviceNo(), content, alarmType);
			SpringUtil.getBean(AliEmailService.class).sendEmail(email,"Vending Machine Alert",s);

			AlertMailHis alertMailHis = new AlertMailHis();
			alertMailHis.setHisId(deviceAlertDto.getHisId());
			alertMailHis.setDeviceId(deviceAlertDto.getDeviceId());
			alertMailHis.setDeviceNo(deviceAlertDto.getDeviceNo());
			alertMailHis.setAlertType(deviceAlertDto.getAlertType());
			alertMailHis.setAlertTime(deviceAlertDto.getAlertTime());
			alertMailHis.setEmail(email);
			alertMailHis.setContent(content);
			alertMailHis.setUpdateTime(new Date());
			alertMailHis.setMerchantId(deviceAlertDto.getMerchantId());
			log.info("alertMail{}",JSON.toJSONString(alertMailHis));
			try {
				alertMailHisMapper.insert(alertMailHis);
			} catch (Exception e) {
				e.printStackTrace();
				log.error("alertMail",e);
			}
			log.info("alertMail2{}",JSON.toJSONString(alertMailHis));
		}
		return exceptionFlag;
	}

	private Boolean checkMailLimit(DeviceAlertDto deviceAlertDto){
		DateTime beginOfDay = cn.hutool.core.date.DateUtil.beginOfDay(new Date());
		LambdaQueryWrapper<AlertMailHis> alertQuery = Wrappers.lambdaQuery();
//		alertQuery.eq(AlertMailHis::getMerchantId,deviceAlertDto.getMerchantId());
		alertQuery.eq(AlertMailHis::getDeviceNo,deviceAlertDto.getDeviceNo());
		alertQuery.between(AlertMailHis::getUpdateTime,beginOfDay,new Date());
		Long aLong = alertMailHisMapper.selectCount(alertQuery);
		log.info("deviceNo{}===>当日告警数量{}",deviceAlertDto.getDeviceNo(),aLong);
		if (aLong.compareTo(10L)>0) {
			log.info("设备接受邮件超过10条{}",deviceAlertDto.getDeviceNo());
			return true;
		}
		return false;
	}


	private String buildEmailBody(String deviceNo, String content ,String alarmType){
		DeviceDetail device = getDevice(deviceNo);
		StringBuilder sb = new StringBuilder();
		sb.append("Alert Type:").append(alarmType).append("<br>");
		sb.append("Alert Content:  ").append(content).append("<br>");
		sb.append("Device ID:").append(deviceNo).append("<br>");
		if(device != null &&StringUtils.isNotBlank(device.getName())){
			sb.append("Device Name:").append(device.getName()).append("<br>");
		}
		if(device != null &&StringUtils.isNotBlank(device.getAddress())){
			sb.append("Device Address:").append(device.getAddress()).append("<br>");
		}

		return sb.toString();
	}

	private DeviceDetail getDevice(String deviceNo){
		LambdaQueryWrapper<DeviceDetail> deviceWrapper = Wrappers.lambdaQuery();
		deviceWrapper.eq(DeviceDetail::getDeviceNo,deviceNo);
		deviceWrapper.last("LIMIT 1");
		return deviceDetailMapper.selectOne(deviceWrapper);
	}

	@Override
	public List<DeviceDetailVo> allDevices() {
		return getDeviceDetails();
	}

	private List<DeviceDetailVo> getDeviceDetails() {
		try {
			String url = SpringUtil.getBean(DeviceProperties.class).getDeviceDetailsUrl();
			RestTemplate restTemplate = new RestTemplate();
			R<List<String>> status = R.status(true);
			ResponseEntity<? extends R> forEntity = restTemplate.getForEntity(url, status.getClass());
			R<List<String>> body = forEntity.getBody();
			List<String> data = body.getData();
			String s = JSON.toJSONString(data);
			List<DeviceDetailVo> deviceDetailVos = JSON.parseArray(s, DeviceDetailVo.class);
			return deviceDetailVos;
		} catch (Exception e) {
			log.error("获取用户邮箱失败",e);
			return new ArrayList<>();
		}
	}
}
